<template>
  <div class="profile">
    <div class="profile-header">
      <h1 class="page-title">
        <el-icon class="title-icon"><User /></el-icon>
        个人资料
      </h1>
    </div>
    
    <div class="profile-content">
      <div class="profile-left">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">基本信息</h3>
          </div>
          <div class="profile-info">
            <div class="avatar-section">
              <el-avatar :size="100" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="user-info">
                <h3 class="user-name">{{ userInfo.realName }}</h3>
                <p class="user-role">{{ getRoleText(userInfo.role) }}</p>
              </div>
            </div>
            
            <el-form 
              ref="profileFormRef"
              :model="profileForm" 
              :rules="profileRules"
              label-width="100px" 
              class="profile-form"
            >
              <el-form-item label="用户名">
                <el-input v-model="profileForm.username" disabled />
              </el-form-item>
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="profileForm.realName" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="profileForm.phone" />
              </el-form-item>
              <el-form-item label="角色">
                <el-tag :type="getRoleType(profileForm.role)" size="large">
                  {{ getRoleText(profileForm.role) }}
                </el-tag>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSaveProfile" :loading="profileLoading">
                  保存信息
                </el-button>
                <el-button @click="handleResetProfile">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      
      <div class="profile-right">
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">修改密码</h3>
          </div>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 操作记录模块已屏蔽 -->
        <!-- <div class="card">
          <div class="card-header">
            <h3 class="card-title">操作记录</h3>
          </div>
          <div class="operation-list">
            <div
              v-for="operation in operationList"
              :key="operation.id"
              class="operation-item"
            >
              <div class="operation-icon">
                <el-icon><component :is="operation.icon" /></el-icon>
              </div>
              <div class="operation-content">
                <div class="operation-title">{{ operation.title }}</div>
                <div class="operation-time">{{ operation.time }}</div>
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Edit, Setting, Login } from '@element-plus/icons-vue'
import { updateUserInfo, changePassword } from '@/api/user'

export default {
  name: 'Profile',
  components: {
    User,
    Edit,
    Setting,
    Login
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const passwordFormRef = ref()
    const profileFormRef = ref()
    const passwordLoading = ref(false)
    const profileLoading = ref(false)
    
    const userInfo = computed(() => store.getters['user/userInfo'] || {})
    
    // 个人信息表单
    const profileForm = reactive({
      username: '',
      realName: '',
      email: '',
      phone: '',
      role: ''
    })
    
    // 个人信息验证规则
    const profileRules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    }
    
    // 密码表单
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 操作记录
    const operationList = reactive([
      {
        id: 1,
        title: '登录系统',
        time: '2025-09-23 10:30:00',
        icon: 'Login'
      },
      {
        id: 2,
        title: '修改个人信息',
        time: '2025-09-22 15:20:00',
        icon: 'Edit'
      },
      {
        id: 3,
        title: '修改密码',
        time: '2025-09-21 09:15:00',
        icon: 'Setting'
      }
    ])
    
    // 获取角色文本
    const getRoleText = (role) => {
      const roleMap = {
        'ADMIN': '管理员',
        'TEACHER': '教师',
        'STUDENT': '学生',
        '管理员': '管理员',
        '教师': '教师',
        '学生': '学生'
      }
      return roleMap[role] || '未知'
    }
    
    // 获取角色类型
    const getRoleType = (role) => {
      const typeMap = {
        'ADMIN': 'danger',
        'TEACHER': 'warning',
        'STUDENT': 'success',
        '管理员': 'danger',
        '教师': 'warning',
        '学生': 'success'
      }
      return typeMap[role] || 'info'
    }
    
    // 保存个人信息
    const handleSaveProfile = async () => {
      if (!profileFormRef.value) return
      
      try {
        const valid = await profileFormRef.value.validate()
        if (!valid) return
        
        profileLoading.value = true
        
        // 调用API保存个人信息
        await updateUserInfo(profileForm)
        
        ElMessage.success('个人信息保存成功')
        
        // 更新store中的用户信息
        store.commit('user/SET_USER_INFO', { ...userInfo.value, ...profileForm })
        
      } catch (error) {
        console.error('保存个人信息失败:', error)
        ElMessage.error('保存个人信息失败')
      } finally {
        profileLoading.value = false
      }
    }
    
    // 重置个人信息表单
    const handleResetProfile = () => {
      if (profileFormRef.value) {
        profileFormRef.value.resetFields()
      }
      // 重新从store加载用户信息
      Object.assign(profileForm, userInfo.value)
    }
    
    // 修改密码
    const handleChangePassword = async () => {
      if (!passwordFormRef.value) return
      
      try {
        const valid = await passwordFormRef.value.validate()
        if (!valid) return
        
        passwordLoading.value = true
        
        // 调用API修改密码，传递当前用户名
        const passwordData = {
          username: userInfo.value.username,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        }
        
        const response = await changePassword(passwordData)
        
        // 检查响应是否成功
        if (response && (response.code === 200 || response.code === 0)) {
          ElMessage.success('密码修改成功')
          // 重置表单
          passwordFormRef.value.resetFields()
        } else {
          ElMessage.error(response?.message || '密码修改失败')
        }
        
      } catch (error) {
        console.error('修改密码失败:', error)
        // 错误信息已经在响应拦截器中处理了，这里不需要再次显示
        // 只需要重置表单状态
      } finally {
        passwordLoading.value = false
      }
    }
    
    // 监听用户信息变化，同步到表单
    watch(userInfo, (newUserInfo) => {
      if (newUserInfo) {
        console.log('用户信息发生变化，同步到表单:', newUserInfo)
        Object.assign(profileForm, newUserInfo)
        console.log('表单数据已更新:', profileForm)
      }
    }, { immediate: true, deep: true })
    
    // 页面加载
    onMounted(async () => {
      // 确保侧边栏在个人资料页面保持打开状态
      store.dispatch('app/openSideBar', { withoutAnimation: false })
      
      // 每次打开个人资料页面都重新获取用户信息，确保数据完整性
      try {
        console.log('开始获取用户信息...')
        await store.dispatch('user/getUserInfo')
        console.log('用户信息加载完成:', userInfo.value)
        
        // 确保表单数据同步
        if (userInfo.value) {
          Object.assign(profileForm, userInfo.value)
          console.log('表单数据已同步:', profileForm)
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        ElMessage.error('加载用户信息失败，请刷新页面重试')
      }
    })
    
    // 监听路由变化，确保在个人资料页面时侧边栏保持打开
    watch(() => route.path, (newPath) => {
      if (newPath === '/profile') {
        store.dispatch('app/openSideBar', { withoutAnimation: false })
      }
    }, { immediate: true })
    
    return {
      passwordFormRef,
      profileFormRef,
      passwordLoading,
      profileLoading,
      userInfo,
      profileForm,
      profileRules,
      passwordForm,
      passwordRules,
      operationList,
      getRoleText,
      getRoleType,
      handleSaveProfile,
      handleResetProfile,
      handleChangePassword
    }
  }
}
</script>

<style lang="scss" scoped>
.profile {
  .profile-header {
    margin-bottom: 24px;
    
    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 12px;
      
      .title-icon {
        font-size: 32px;
        color: #409eff;
      }
    }
  }
  
  .profile-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
    
    .card {
      background: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      margin-bottom: 24px;
      
      .card-header {
        margin-bottom: 20px;
        padding-bottom: 12px;
        border-bottom: 1px solid #f0f0f0;
        
        .card-title {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          margin: 0;
        }
      }
    }
  }
  
  .profile-info {
    .avatar-section {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 30px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
      
      .user-avatar {
        background: #409eff;
        color: white;
        font-size: 40px;
      }
      
      .user-info {
        .user-name {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 8px 0;
        }
        
        .user-role {
          font-size: 16px;
          color: #909399;
          margin: 0;
        }
      }
    }
    
    .profile-form {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }
  
  .operation-list {
    .operation-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .operation-icon {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #606266;
      }
      
      .operation-content {
        flex: 1;
        
        .operation-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .operation-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .profile .profile-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .profile {
    .profile-header .page-title {
      font-size: 24px;
    }
    
    .profile-content .card {
      padding: 16px;
    }
    
    .profile-info .avatar-section {
      flex-direction: column;
      text-align: center;
      gap: 16px;
    }
  }
}
</style>
